#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netdb.h>
#include<unistd.h>
#include <pthread.h>
#include <common.h>
void* myread(void* arg){
    int acc_sock=*(int *)arg;



    recvLogic(acc_sock);
    printf("退出线程:%d\n",acc_sock);
    return NULL;
}
void *mywrite(void* arg){
    int acc_sock=*(int *)arg;
    char wbuffer[1024]={0};
    int wrbt;
    while(1){
        bzero(wbuffer,1024);
        int s=scanf("%s",wbuffer);
        wrbt=write(acc_sock,wbuffer,sizeof(wbuffer));
        if(wrbt<0){
            printf("close connect:%d,%d\n",acc_sock,s);
            break;
        }

    }
    return NULL;
}

int main(int argc, char *argv[])
{

    if(test()==1){
        return 0;
    }

    struct sockaddr_in s_add,d_add;
    unsigned short port=1122;
    int sock=socket(AF_INET,SOCK_STREAM,0);
    socklen_t so_size;
    if(sock==-1){
        printf("fail create socket!\n");

    }
    bzero(&s_add,sizeof(struct sockaddr_in));
    s_add.sin_family=AF_INET;
    s_add.sin_addr.s_addr=htonl(INADDR_ANY);
    s_add.sin_port=htons(port);
    if(-1==bind(sock,(struct sockaddr *)&s_add,sizeof(struct sockaddr))){
        printf("fail bind socket!\n");

    }
    if(-1==listen(sock,5)){
        printf("fail listen socket!\n");
    }
    while(1){
        so_size=sizeof(struct sockaddr_in);
        printf("wait to connect............\n");
        int acc_sock=accept(sock,(struct sockaddr *)&d_add,&so_size);
        if(acc_sock==-1){
            printf("fail accept socket!\n");
            exit(0);
        }
        pthread_t p,p2;

        printf("ip:%s\n",inet_ntoa(d_add.sin_addr));
        int s=write(acc_sock,"welcome to server!",sizeof("welcome to server!"));
        pthread_create(&p,NULL,myread,&acc_sock);
        pthread_create(&p2,NULL,mywrite,&acc_sock);

        printf("%d\n",s);

    }
    printf("hello %d\n",sock);
    close(sock);
    return 0;
}
